# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
from urllib.parse import urljoin
from datetime import datetime
import logging
import traceback
import json

_logger = logging.getLogger(__name__)



class EmailProxy(models.Model):
    _name = 'email.proxy'
    _description = 'Email Proxy'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _rec_name = 'name'
    _order = 'create_date desc'


    name = fields.Char(string='Workflow')
    # email相关字段
    email_from = fields.Char(string='Email From', tracking=True)
    email_to = fields.Char(string='Email To', tracking=True)
    email_cc = fields.Char(string='Email Cc', tracking=True)
    email_subject = fields.Char(string='Email Subject', tracking=True)
    email_attachment_ids = fields.Many2many('ir.attachment', string='Email Attachment', tracking=True)
    email_date = fields.Datetime(string='Email Date', tracking=True)
    email_origin_data = fields.Html(string='Email Origin Data')
    email_message_id = fields.Char('Email Message ID', tracking=True)
    send_email_ids = fields.Many2many('mail.mail', string='Send Email', compute='_compute_send_email_ids')
    # order相关字段
    state = fields.Selection([
        ('draft', '草稿'),
        ('ocr_recognition_success', 'OCR 识别成功'),
        ('order_generation', '订单生成'),
        ('ocr_recognition_fail', 'OCR 识别失败'),
        ('system_error', '系统异常'),
    ], default='draft', string='Status', tracking=True)

    ocr_proxy_ids = fields.One2many('ocr.proxy', 'email_id', string='OCR Proxy')
    order_line_ids = fields.One2many('order.model', 'email_id', string='Order Line')


    def build_header_data(self, data, header_data):
        for k, v in data.items():
            header_data[k] = v
        return header_data

    def build_invoice_line_data(self, data):
        index = 1
        invoice_line_data = []
        for i in data:
            tmp_dict = {}
            tmp_dict['line_number'] = str(index*10).zfill(5)
            tmp_dict['description'] = i.get('description', None)
            tmp_dict['valid_from'] = i.get('start_date', None)
            tmp_dict['valid_to'] = i.get('end_date', None)
            tmp_dict['price'] = i.get('price', None)
            tmp_dict['quantity'] = i.get('quantity', None)
            tmp_dict['tax_code'] = i.get('tax', None)
            tmp_dict['tax_rate'] = i.get('tax_rate', None)
            invoice_line_data.append(tmp_dict)
            index += 1
        return invoice_line_data

    def transfer_header_data(self, header_data):
        new_header_data = {
            'custom_code': header_data.get('account_number',None),
            'currency_code': header_data.get('currency_code',None),
            'delivery_date': header_data.get('delivery_date',None),
            'reference_number': header_data.get('reference_number',None),
            'invoice_title': header_data.get('document_title',None),
            'due_date': header_data.get('due_date',None),
            'invoice_number': header_data.get('invoice_number',None),
            'card_number': header_data.get('card_number',None),
            'terms': header_data.get('terms',None),
            'type': header_data.get('type',None),
            'purchase_order': header_data.get('purchase_order_number',None),
            'invoice_date': header_data.get('date',None),
            'total_amount': header_data.get('total',None),
            'vendor_name': header_data.get('name',None),
            'vendor_email': header_data.get('email',None),
            'vendor_account_number': header_data.get('account_number',None),
            'vendor_address': header_data.get('address',None),
            'fax_number': header_data.get('fax_number',None),
            'web': header_data.get('web',None),
            'bank_name': header_data.get('bank_name',None),
            'bank_number': header_data.get('bank_number',None),
            'bank_swift': header_data.get('bank_swift',None),
            'ocr_score': header_data.get('ocr_score',None),
            'address': header_data.get('address',None),
            'vat_number': header_data.get('vat_number',None),
            'company': header_data.get('name',None),
        }

        return new_header_data


    def create_order(self):
        try:
            invoice_line_data = {}
            order_obj_list = []
            data_list = [{'ocr_id':i.id,'data':i.json_source_data}for i in self.ocr_proxy_ids if i.choose_ocr]
            for i in data_list:
                header_data = {}
                for k, v in eval(i['data']).items():
                    if k == 'line_items':
                        invoice_line_data = self.build_invoice_line_data(v)
                    elif k in ['bill_to', 'meta', 'payment', 'ship_to', 'vendor']:
                        header_data = self.build_header_data(v, header_data)
                    else:
                        if v:
                            header_data[k] = v

                new_header_data = self.transfer_header_data(header_data)
                new_header_data['email_id'] = self.id
                new_header_data['ocr_id'] = i['ocr_id']
                order_obj = self.env['order.model'].create([{**new_header_data, 'invoice_line_ids':[(0, 0, i) for i in invoice_line_data]}])
                order_obj_list.append(order_obj)

            if len(order_obj_list):
                return {
                    "type": "ir.actions.client",
                    "tag": "display_notification",
                    "params": {
                        "title": _("Success"),
                        "type": "success",
                        "message": _(f"{len(order_obj_list)}订单已生成"),
                        "sticky": False,
                        'next': {'type': 'ir.actions.act_window_close'}
                    },
                }
        except Exception as e:
            _logger.error(traceback.format_exc())
            return {
                "type": "ir.actions.client",
                "tag": "display_notification",
                "params": {
                    "title": _("Fail"),
                    "type": "danger",
                    "message": _(f"生成订单报错-{e}"),
                    "sticky": False,
                    'next': {'type': 'ir.actions.act_window_close'}
                },
            }

    @api.model
    def message_new(self, msg_dict, custom_values=None):
        if custom_values is None:
            custom_values = {}
        if msg_dict.get('body'):
            msg_dict.pop('body')
        attachments = msg_dict.get('attachments')
        values = {
            # 'name': msg_dict.get('subject') or _("No Subject"),
            'email_subject': msg_dict.get('subject', ''),
            'email_from': msg_dict.get('email_from'),
            'email_cc': msg_dict.get('cc', ''),
            'email_to': msg_dict.get('to', ''),
            'email_date': msg_dict.get('date'),
            'email_message_id': msg_dict.get('message_id'),
            'email_origin_data': self.get_email_origin_data(msg_dict),
        }
        mail_obj = super(EmailProxy, self).message_new(msg_dict, values)
        create_data = [{'raw':i.content,'res_id':mail_obj.id,'res_model':self._name,'name':i.fname,'type':'binary'} for i in attachments]
        attachment_ids = self.env['ir.attachment'].sudo().create(create_data)
        mail_obj.email_attachment_ids = [(6, 0, attachment_ids.ids)]
        return mail_obj

    def get_email_origin_data(self, msg_dict):
        json_object = {}
        for i, v in msg_dict.items():
            if i != 'attachments':  # 附件源数据占用内存过大，浏览器卡顿，故不显示
                json_object[i] = v
        # return self.json_convert_html(json_object)

    def _compute_send_email_ids(self):  # fixme 邮件回调状态需要优化, 以及邮件发送后不展示在右侧消息栏中
        for rec in self:
            send_mail_objs = self.env['mail.mail'].sudo().search([('res_id', '=', rec.id), ('model', '=', self._name)])
            rec.send_email_ids = [(6, 0, send_mail_objs.ids)]

    def handle_proxy_email(self):
        self.env['fetchmail.server'].sudo()._fetch_mails()

    # def create(self, vals):
    #     vals['order_number'] = self.env['ir.sequence'].sudo().next_by_code('email_proxy_sequence') or _('New')
    #     res = super(EmailProxy, self).create(vals)
    #     return res

    def ocr_api_recognition(self):
        context = {'invisible_fields':True}
        return {
            'name': '确认进行OCR识别？',
            'view_mode': 'form',
            'res_model': 'ocr.proxy',
            'target': 'new',
            'type': 'ir.actions.act_window',
            'context': context
        }

